package cn.edu.gznu.wecampus.core.utils;

import java.util.Date;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JwtUtils {
	
    public static boolean verify(String token, String userId) {
    	return verify(token, userId, userId);
    }
	
    public static boolean verify(String token, String userId, String secret) {
        try {
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                .withClaim("userId", userId)
                .build();
            // 效验TOKEN
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }
 
    public static String getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
    
    public static String sign(String userId) {
    	// 默认30天有效
    	return sign(userId, userId, 60 * 60 * 24 * 30);
    }
    
    public static String sign(String userId, String secret) {
    	// 默认30天有效
    	return sign(userId, secret, 60 * 60 * 24 * 30);
    }
 
    public static String sign(String userId, String secret, long expireSeconds) {
        Date date = new Date(System.currentTimeMillis() + expireSeconds * 1000);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create()
        	.withClaim("userId", userId)
            .withExpiresAt(date)
            .sign(algorithm);
    }
}
